package myTest.sort;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Date;

/**
 * 把一个目录和其子目录下的所有指定后缀的文件的编码由GBK转换成UTF-8
 * 
 * 
 * java Enc fromDir txt ini <br>
 * java Enc `pwd` txt ini
 * 
 * @author chenwei
 * 
 */
public class Enc {
	private static final String man = "java Enc `pwd` txt ini";

	public static void main(String[] args) throws IOException {
		if (args.length < 2 || args[0].contains("--help")) {
			System.out.println(man);
			return;
		}

		File fromDir = new File(args[0]);
		File toDir = new File(fromDir, "changedEncoding" + new Date().getTime());
		toDir.mkdirs();
		String inEncode = "gbk";
		String outEncode = "utf-8";

		File[] files = fromDir.listFiles();
		if (files == null) {
			System.out.println(man);
			return;
		}

		BufferedReader bufr = null;
		BufferedWriter bufw = null;
		for (File f : files) {
			for (int i = 1; i < args.length; i++) {
				if (!f.getName().endsWith(args[i]))
					continue;

				bufr = new BufferedReader(new InputStreamReader(new FileInputStream(f), inEncode));
				bufw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(toDir, f.getName())), outEncode));

				String line = null;
				while ((line = bufr.readLine()) != null) {
					bufw.write(line);
					bufw.newLine();
				}
				if (bufw != null)
					bufw.close();
				if (bufr != null)
					bufr.close();
			}
		}
	}
}
